package cn.j0n4than.api.controller.api.auth;

import cn.j0n4than.api.config.ResponseConfig;
import cn.j0n4than.api.entity.Admin;
import cn.j0n4than.api.entity.Auth;
import cn.j0n4than.api.entity.pojo.UserLoginPojo;
import cn.j0n4than.api.utils.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author jonathan
 */
@Slf4j
@RestController
@RequestMapping("/api/auth/admin")
public class AuthAdminController extends AuthBaseController {

    @PostMapping("/login")
    public Response login(@Validated @RequestBody UserLoginPojo userLoginPojo, BindingResult validateResult, HttpServletRequest request) {
        Response response = Response.response();

        //获取验证器错误
        if (validateResult.hasErrors()) {
            assert validateResult.getFieldError() != null;
            String message = validateResult.getFieldError().getDefaultMessage();
            return response.setStatus(ResponseConfig.ERROR).setMessage(message);
        }

        Admin admin = adminService.login(userLoginPojo.username, userLoginPojo.password);
        if (admin != null) {
            try {
                Auth auth = new Auth();
                auth.userId = admin.id;
                auth.ip = request.getRemoteAddr();
                //设置token过期时间
                auth.expire = new Date((new Date()).getTime() + 3600000 * 24);
                auth.type = Auth.TYPE_ADMIN;
                String json = objectMapper.writeValueAsString(auth);
                //加密token
                String token = desUtil.encrypt(json);

                //不返回密码
                admin.password = null;

                //更新登陆信息
                admin.lastLoginAt = new Date(System.currentTimeMillis());
                admin.lastLoginIp = request.getRemoteAddr();
                adminService.update(admin.id, admin);

                response.setStatus(ResponseConfig.SUCCESS)
                        .setMessage("登陆成功")
                        .setResult("user", admin)
                        .setResult("token", token);
            } catch (JsonProcessingException e) {
                response.setStatus(ResponseConfig.ERROR)
                        .setMessage("用户名或密码错误");

                log.error("加密Token失败");
                log.error(e.getMessage());
            }
        } else {
            response.setStatus(ResponseConfig.ERROR)
                    .setMessage("用户名或密码错误");
        }

        return response;
    }

}
